// SlagCar/ApproveList/ApproveList.js
let listBehavior = require('../../behavior/list')
const req = require('../../utils/request');
Page({
  behaviors: [ listBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {
    system_id: wx.getStorageSync('system_id') || 1164,  //231215 yan 图片字段只返回文件名时，需要系统号拼接图片地址
    baseURL: req.baseURL,

    tabActive: 0, //标签选中索引
    baseQuery: [],

    returnShow: false,
    returnField: [
      {field_id: 'staff_mark',label: '退审原因',type: 'textarea',is_null: false},],
    returnData: {},
  },
  //获取数据
  getDataList(){
    let {page,limit,filter,list,baseQuery} = this.data
    let total = 0,
      obj = {};
    let url = 'DynamicQuery/query_dynamic_v3',
      post = {"oby":"muck_waybill_main.row_id","table_id":"muck_waybill_main",page,limit},
      where = [...baseQuery];

    if (filter === '审核中'){
      where.push(
        {CompareWith:"muck_waybill_main.is_Checked",Operator:"=",CompareValue:false,"or":0},
        {CompareWith: "muck_waybill_main.auditing_1_time", Operator: "is null", CompareValue: "", or: 0}
      )
    }
    if (filter === '已审核'){
      where.push(
        {CompareWith:"muck_waybill_main.is_Checked",Operator:"=",CompareValue:true,"or":0},
      )
    }
    if (filter === '退回'){
      where.push(
        {CompareWith:"muck_waybill_main.is_Checked",Operator:"=",CompareValue:false,"or":0},
        {CompareWith: "muck_waybill_main.auditing_1_time", Operator: "is not null", CompareValue: "", or: 0}
      )
    }
    if (where.length) post.SearchWhere = {filters: where,type: 'and'};
    wx.$post(3,url,post).then(res => {
      if (res.errcode != 0) return;
      if (res.data.row){
        total = res.data.total;
        let rows = res.data.row;
        if(page !== 1) rows = [ ...list,...rows, ]
        obj = {total,list: rows,page};
      }
      this.setData(obj);
    });
  },

  //231229 yan 审批改为审核
  bindAuditing(e){
    let {rid,state} = e.currentTarget.dataset;
    if (state === '审核'){
      wx.showModal({
        title: '审核',
        content: '确定审核该运单？',
        success: res =>{
          if (res.confirm){
            wx.showLoading({mask: true})
            //提交审核
            this.updateAuditing(rid,true).then(() => {
              wx.$toast('提交成功');
              this.getDataList();
            })
          }
        }
      })
    } else {
    //  提交修改管理员备注
    this.setData({
      returnShow: true,
      returnRid: rid
    })
    }
  },
  updateAuditing(rid,isAgainst){
    return new Promise(resolve => {
      let url = 'Custom/update_entity_auditing',
        post = {"table_id": 'muck_waybill_main', "row_id": rid,"auditing_level": 1, "is_auditing": isAgainst};
      wx.$post(1,url,post).then(res => {
        if (res.errcode != 0) return;
        resolve();
      })
    })
  },
  catchTap(){},
  bindClose(){
    this.setData({returnShow: false})
  },
  bindChange(e){
    let {field,val} = e.detail,
      id = field.field_id || field.fieldName;

    //赋值
    this.data.returnData[id] = val
  },
  bindReturn(){
    let {returnRid,returnData} = this.data,
      url = 'DynamicUpdate/dynamic_update_v3',
      post = {
        table: {
          table_id: 'muck_waybill_main',
          entitys: [{
            details: [],
            entity: {
              ...returnData,
              row_id: returnRid
            }
          }]
        }};
    if (!returnData.staff_mark) {
      wx.$toast('请输入退审原因');
      return
    }
    let pms = [this.updateAuditing(returnRid,false),wx.$post(3,url,post)];
    Promise.all(pms).then(res =>{
      let flag = false;
      res.forEach(item =>{
        if (item.errcode != 0) flag = true;
      })
      if (flag) return;
      wx.$toast('已退审');
      this.setData({returnShow: false})
    })
    this.updateAuditing(returnRid,false)
    wx.$post(3,url,post).then(res =>{
      if (res.errcode != 0) return;
      wx.$toast('已退审');
      this.setData({returnShow: false})
    })


  },


  //提交审批
  bindApprove(e){
    let {rid,state} = e.currentTarget.dataset,
      title = state === '同意' ? '审核' : '退审'
    wx.showModal({
      title,
      content: `确定${title}该订单？`,
      success: async (res) => {
      if(res.confirm) {
        let is_operate = false;
        wx.showLoading({mask: true})
        await this.getApproveOperate(rid).then(res => is_operate = res);
        if (is_operate){
          this.updateApprove(rid,state).then(() => {
            wx.$toast('提交成功');
            this.getDataList();
          })
         /* this.getApproveProcess().then(process_id => {
          })*/
        }else {
          wx.$toast('抱歉，您没有权限审核。');
        }
      }
    },
    })
  },

  //查看是否有审批权限
  getApproveOperate(rid){
    return new Promise(resolve => {
      let url = 'Approval_process/get_approval_process_operate',
        post = {"table_id":"muck_waybill_main","row_id": rid};
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        resolve(res.data.row && res.data.row[0].is_operate);
      })
    })
  },


  //获取审批号
  getApproveProcess(){
    return new Promise(resolve => {
      let url = 'Approval_process/query_approval_process',
        post = {
          page: 1,
          oby: "process_id desc",
          limit: 1,
          SearchWhere: [
            {
              CompareValue: 'muck_waybill_main',
              CompareWith: 'table_id',
              Operator: '=',
              or: 0
            },
            {
              CompareValue: true,
              CompareWith: 'status',
              Operator: '=',
              or: 0
            },
          ]
        },
        {process_id} = this.data;
      if (process_id){
        resolve(process_id);
        return
      }
      wx.showLoading({mask: true});
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        if (res.data.row[0]) process_id = res.data.row[0].process_id;
        this.data.process_id = process_id;
        resolve(process_id);
        wx.hideLoading();
      })
    })
  },

  //提交审批
  updateApprove(rid,state){
    // {process_id} = this.data,
      let  url = 'Approval_process/update_approval_process_log',
      post = {
        process_id:"",
        "table_id": "muck_waybill_main",
        "row_id": rid,
        "sh_state": state,
        "next_sh_id":"",
        "next_sh_name":"",
        "sh_mark":""
      };
    return new Promise(resolve => {
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        resolve();
      })
    })
  },

  //预览照片
  previewImg(e){
    let {list,i} = e.currentTarget.dataset;
    list = list && list.split(',') || []
    let {  system_id,baseURL } = this.data,
      imgs = [];
    //231221 yan 修改 图片字段只返回文件名称，通过系统号拼接图片访问地址
    list.forEach(item => {
      let name = item.substring(item.lastIndexOf('/')+1);
      imgs.push(`${baseURL}/files/${system_id}/${name}`)
    });
    //231221 end
    wx.previewImage({
      current: imgs[i],
      urls: imgs
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let baseQuery = wx.getStorageSync('approveQuery');
    wx.removeStorageSync('approveQuery');
    this.setData({baseQuery})
    this.getDataList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
